package com.xkh.xkh;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.support.multidex.MultiDex;

import com.baidu.location.LocationClient;
import com.baidu.mapapi.SDKInitializer;
import com.xkh.xkh.ACache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.orm.SugarApp;
import com.orm.SugarRecord;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import java.io.File;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.ExecutorService;

import chat.network.tcp.PushService;
import de.mindpipe.android.logging.log4j.LogConfigurator;
import managers.Constants;
import managers.DatabaseManager;
import managers.SQLiteHelper;
import managers.UIHandler;
import managers.UserInfo;
import model.BeiWang;
import model.OwnUser;
import utils.TimeUtil;


/**
 * Created by 凯 on 2015/10/12.
 */
public class MyApplication extends SugarApp {

    // 应用程序单例，使用Context方便
    public static MyApplication shareApp;

    public static ACache aCache = null;
    // 全局Context获得
    public static MyApplication share() {
        return shareApp;
    }
    public static boolean isExitMust  = false;

    public static LocationClient mLocClient ;

    public static DisplayImageOptions options;
    static
    {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.defalut_img) //设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.defalut_img)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.defalut_img)  //设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)//设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中
                .considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
                .imageScaleType(ImageScaleType.EXACTLY)//设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
                .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
                .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
                .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
                .build();//构建完成
    }


    public static Typeface iconfont;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SDKInitializer.initialize(getApplicationContext());
        // 检查错误
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                ex.printStackTrace();
                Logger log = Logger.getLogger(MyApplication.class);
                log.error("error",ex);
            }
        });

        System.out.println("启动application:" + android.os.Process.myPid());

        shareApp = this;
        // 初始化数据库
        DatabaseManager.initializeInstance(new SQLiteHelper(15));
        // 初始化界面控制模块
        UIHandler.uiHandler = new UIHandler();
        initdata();
        initImageLoader(getApplicationContext());
        aCache  = ACache.get(this);
        configLog("log");
        iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");

        mLocClient = new LocationClient(this);
    }

    private void configLog(String logFileNamePrefix) {
        LogConfigurator logConfigurator = new LogConfigurator();
        logConfigurator.setFileName(Environment.getExternalStorageDirectory()
                + File.separator + "xkh" + File.separator + "logs"
                + File.separator + (logFileNamePrefix == null ? "" : logFileNamePrefix) + "_error.txt");
        logConfigurator.setRootLevel(Level.DEBUG);
        logConfigurator.setLevel("org.apache", Level.ERROR);
        logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
        logConfigurator.setMaxFileSize(1024 * 1024 * 2);
        logConfigurator.setImmediateFlush(true);
        logConfigurator.configure();
    }


    private void initImageLoader(Context context) {
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());

    }

    private void initdata() {
        if (getOwnUser() == null) return;
        if (getOwnUser().isLogined()) {
            // 初始化推送服务
            initPushServise();
        }

    }

    // 初始化推送服务
    private void initPushServise() {
        Intent intent = new Intent(this,PushService.class);
        intent.putExtra(PushService.SERVICE_ACTION, PushService.ACTION_CONNECTION);
        startService(intent);
    }

    public static OwnUser getOwnUser()
    {
        OwnUser ownUser = null;
        {
            List<OwnUser> ownUsers = SugarRecord.listAll(OwnUser.class);
            if (!ownUsers.isEmpty()) {
                ownUser = ownUsers.get(0);
            }
        }
        return ownUser;
    }


    /**
     * 检查当前网络是否可用
     *
     * @return
     */

    public boolean isNetworkAvailable()
    {
        Context context = this;
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null)
        {
            return false;
        }
        else
        {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0)
            {
                for (int i = 0; i < networkInfo.length; i++)
                {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

